/*
 * BaseStatisticsFragment.java
 * business
 *
 * Created by ChenTao on 2017/2/24.
 *
 * Copyright (c) 2017年 yidiandao. All rights reserved.
 */

package com.yidiandao.business.base;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;

import com.squareup.leakcanary.RefWatcher;
import com.yidiandao.business.BusinessApplicationLike;
import com.yidiandao.business.data.net.NetBiz;
import com.yidiandao.business.utils.UmengUtils;

/**
 * 统计的Fragment
 *
 * <p>Created by ChenTao(chentao7v@gmail.com) on 2017/2/24 17:09
 */
public abstract class RootFragment extends Fragment {

    private static final String STATE_SAVE_IS_HIDDEN = "STATE_SAVE_IS_HIDDEN";

    protected Activity mActivity;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = getActivity();

        // 切换字体时，app崩溃的bug
        setRetainInstance(true);

        if (savedInstanceState != null) {
            boolean isSupportHidden = savedInstanceState.getBoolean(STATE_SAVE_IS_HIDDEN);
            FragmentTransaction transaction = getFragmentManager().beginTransaction();
            if (isSupportHidden) {
                transaction.hide(this);
            } else {
                transaction.show(this);
            }
            transaction.commit();
        }
    }

    /** Fragment销毁之后默认取消网络请求 */
    protected boolean cancelRequest() {
        return true;
    }

    /** 在该方法中初始化Fragment中的View */
    protected abstract void initViews();

    /** 返回Fragment布局Id */
    protected abstract int getLayoutId();

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean(STATE_SAVE_IS_HIDDEN, isHidden());
    }

    @Override
    public void onResume() {
        super.onResume();
        UmengUtils.onPageStart(getPagerTag());
    }

    @Override
    public void onPause() {
        super.onPause();
        UmengUtils.onPageEnd(getPagerTag());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 页面销毁时取消网络请求
        if (TextUtils.isEmpty(getPagerTag())) {
            throw new IllegalArgumentException(this.getClass().getSimpleName()
                    + " 's method getPagerTag() method can not return null,please check you code!");
        }
        if (cancelRequest()) {
            NetBiz.cancelRequest(getPagerTag());
        }

        RefWatcher refWatcher = BusinessApplicationLike.getRefWatcher();
        refWatcher.watch(this);
    }

    public abstract String getPagerTag();
}
